package com.example.netty.io.server

import com.example.netty.io.core.DataHandlerAdapter
import com.example.netty.io.core.IMessageListener
import com.example.netty.io.core.NettyConfigure
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerAdapter
import io.netty.channel.ChannelInitializer
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.DelimiterBasedFrameDecoder
import io.netty.handler.codec.json.JsonObjectDecoder
import io.netty.handler.codec.string.StringDecoder
import io.netty.handler.codec.string.StringEncoder
import io.netty.handler.timeout.IdleStateHandler
import java.util.concurrent.TimeUnit

class ServerChannelHandler(private val iMessageListener: IMessageListener) :
    ChannelInitializer<SocketChannel>() {

    override fun initChannel(ch: SocketChannel?) {
        ch?.let { channel ->
            val pipeline = channel.pipeline()
            pipeline.addLast(
                IdleStateHandler(
                    NettyConfigure.readIdleTime,
                    NettyConfigure.writeIdleTime,
                    NettyConfigure.allIdleTime,
                    TimeUnit.MILLISECONDS
                ),
//                DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("###".toByteArray())),
                StringEncoder(),
                StringDecoder(),
                DataHandlerAdapter("Server", iMessageListener),
            )
        }
    }
}